<script setup lang="ts">
import { onMounted, ref, registerRuntimeCompiler, watch } from "vue";
import type {
  DeptModel,
  EmpExprModel,
  EmpModel,
  EmpModelArray,
  PaginationParam,
  SearchEmpModel
} from "@/api/model/model";
import { addApi, deleteApi, queryInfoApi, queryPageApi, updateApi } from "@/api/emp";
import { ElMessage, ElMessageBox } from "element-plus";
import { queryAllApi } from "@/api/dept";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";

//定义上传
const imageUrl = ref("");

//服务器响应上传文件请求处理成功后触发事件函数，开发者通过这个函数获取废物器响应的数据
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  //response:调用服务器上传响应对象
  //将服务器返回的上传图片地址更新到模型中
  emp.value.image = response.data;
};

//上传前调用的逻辑校验函数，校验文件后缀名和文件大小等信息
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("上传的文件只支持jpeg或png图片格式");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("上传的文件大小不能超过10MB");
    return false;
  }
  return true;
};

const empSearch = ref<SearchEmpModel>({
  name: "",
  gender: "",
  begin: "",
  end: "",
  date: []
});
//侦听empSearch的date属性
watch(() => empSearch.value.date, (newVal, oldVal) => {
  if (newVal.length > 0) {
    empSearch.value.begin = newVal[0];
    empSearch.value.end = newVal[1];
  } else {
    empSearch.value.begin = "";
    empSearch.value.end = "";
  }
});

//查询点击事件
const queryPage = async () => {
  //调用远程分页查询接口查询数据
  const result = await queryPageApi(
    empSearch.value.begin,
    empSearch.value.end,
    empSearch.value.gender,
    empSearch.value.name,
    pagination.value.currentPage,
    pagination.value.pageSize
  );

  //判断接口调用是否成功
  if (result.code) {
    //成功，更新书数据员工列表和总条数
    empList.value = result.data.rows;
    pagination.value.total = result.data.total;
  } else {
    //失败，提示错误信息
    ElMessage.error("好像没有调用成功，出错了呢(┬┬﹏┬┬)");
  }
};

//钩子函数
onMounted(() => {
  queryPage();
});

//清空点击事件
const reset = () => {
  //重置搜索条件对象
  empSearch.value = {
    name: "",
    gender: "",
    begin: "",
    end: "",
    date: []
  };
  //重新查询数据
  queryPage();
};

//分页组件每页大小改变触发的事件
const handleSizeChange = (val: number) => {
  //将每个大小改变的值更新到模型数据中
  pagination.value.pageSize = val;
  //重新查询数据
  queryPage();
};

//分页组件每页页码改变触发的事件
const handleCurrentChange = (val: number) => {
  //将页码改变值更新到模型数据
  pagination.value.currentPage = val;
  //重新查询数据
  queryPage();
};

/*列表展示和分页组件数据模型配置逻辑处理*/
//定义响应式变量
const empList = ref<EmpModelArray>();//员工列表
const pagination = ref<PaginationParam>({
  //分页对象
  currentPage: 1,
  pageSize: 5,
  total: 0
});

/*新增或修改对话框操作数据逻辑*/
//定义变量
const dialogFormVisible = ref<Boolean>(false);//新增或修改对话框是否显示模型数据
const emp = ref<EmpModel>({
  //定义新增或修改员工对象
  username: "",
  password: "",
  name: "",
  gender: "",
  phone: "",
  job: "",
  salary: "",
  image: "",
  entryDate: "",
  deptId: "",
  exprList: []
});
const formTitle = ref<string>("");//新增或修改对话框标题
const labelWidth = ref<string>("80px");//设置新增或修改对话框表单元素宽度

//点击新增员工弹出对话框事件
const addPopDialog = () => {
  //设置对话框标题
  formTitle.value = "新增员工";
  emp.value = {
    //定义新增或修改员工对象
    username: "",
    password: "",
    name: "",
    gender: "",
    phone: "",
    job: "",
    salary: "",
    image: "",
    entryDate: "",
    deptId: "",
    exprList: []
  };
  //设置对话框显示
  dialogFormVisible.value = true;

  queryDeptAll();
};

//定义变量
const jobList = ref([
  { name: "班主任", id: 1 },
  { name: "讲师", id: 2 },
  { name: "学工主管", id: 3 },
  { name: "教研主管", id: 4 },
  { name: "咨询师", id: 5 },
  { name: "其他", id: 6 }
]);
const deptList = ref<DeptModel[]>();//部门列表数据
//查询所有部门列表数据进行初始化
const queryDeptAll = async () => {
  //远程调用部门列表查询数据
  let result = await queryAllApi();
  //将部门列表数据更新到模型deptList中
  deptList.value = result.data;
};

//添加工作经历点击事件
const addWorkItem = () => {
  //给员工对象属性工作经历数组添加元素即可
  emp.value.exprList.push({
    exprDate: [],
    begin: "",
    end: "",
    company: "",
    job: ""
  });
};
//watch监听emp，有任何改变更新每个工作经历expr对象中的begin和end
// watch(
//   emp,
//   (newEmp: EmpModel[], oldEmp: EmpModel[]) => {
//     //新的工作经历集合有效才更新
//     if (newEmp.exprList && newEmp.exprList.length) {
//       //遍历工作经历集合每个元素更新时间
//       newEmp.exprList.forEach((expr) => {
//         if (expr.exprDate && expr.exprDate.length) {
//           expr.begin = expr.exprDate[0];
//           expr.end = expr.exprDate[1];
//         } else {
//           expr.begin = "";
//           expr.end = "";
//         }
//       });
//     }
//   },
//   { deep: true}
// );
watch(
  emp.value.exprList,
  (newExprList: EmpExprModel[], oldExprList: EmpExprModel[]) => {
    //新的工作经历集合有效才更新
    if (newExprList && newExprList.length) {
      //遍历工作经历集合每个元素更新时间
      newExprList.forEach((expr) => {
        if (expr.exprDate && expr.exprDate.length) {
          expr.begin = expr.exprDate[0];
          expr.end = expr.exprDate[1];
        } else {
          expr.begin = "";
          expr.end = "";
        }
      });
    }
  },
  { deep: true }
);

//删除工作经历点击事件
const delWorkItem = (expr: EmpExprModel) => {
  //1.先获取删除工作经历对象expr在数组emp.value.exprList集合中索引位置，语法：数组indexof(元素对象)
  let index = emp.value.exprList.indexOf(expr);
  //2.根据索引位置删除 数组.splic(索引位置，删除多个元素)
  if (index != -1) {
    emp.value.exprList.splice(index, 1);
  }
};

//保存或修改点击事件实现数据库数据操作
const saveOrUpdate = async () => {
  //1.远程调用员工添加接口
  let result;
  if (emp.value.id) {
    result = await updateApi(emp.value)
  } else {
    result = await addApi(emp.value);
  }
  //2.判断是否添加成功
  if (result.code) {
    //2.1成功
    //关闭对话框
    dialogFormVisible.value = false;
    //重置表单数据
    emp.value = {
      //定义新增或修改员工对象
      username: "",
      password: "",
      name: "",
      gender: "",
      phone: "",
      job: "",
      salary: "",
      image: "",
      entryDate: "",
      deptId: "",
      exprList: []
    };
    //重新查询数据
    queryPage();

    //提示成功
    ElMessage.success("添加成功");
  } else {
    //2.2不成功，提示错误信息
    ElMessage.error(result.msg);
  }
};

//列表中编辑点击函数事件
const upDateDialog = async (id:number) => {
  await queryDeptAll();
  //设置新增或修改对话框标题
  formTitle.value = "修改员工";
  //远程调用根据id查询员工对象数据接口
  //接口调用
  const result = await queryInfoApi(id);
  //判断是否成功
  if (result.code) {
    //成功，将获取的数据更新到emp中
    emp.value = result.data;
    //根据每个工作经历的begin和end更新每个工作经历的exprDate
    //判断工作经历集合是否有效
    if( emp.value.exprList && emp.value.exprList.length) {
      //遍历工作经历集合
      emp.value.exprList.forEach((expr) => {
        //每个工作经历的begin和end更新每个工作经历的exprDate
        expr.exprDate = [expr.begin,expr.end];
      });
    }
    //显示对话框
    dialogFormVisible.value = true;
  } else {
    //失败，显示失败消息
    ElMessage.error(result.msg)
  }
};

const genderList = [
  { name: "男", value: 1 },
  { name: "女", value: 2 },
];

//定义要删除多个员工的id列表
const deleteIds = ref<(number | undefined)[]>([]);
//复选框勾选改变事件函数
const handleSelectionChange = (selectedEmpList: EmpModel[]) => {
  //先重置id列表
  deleteIds.value = [];
  //根据获取到的所有勾选的员工列表提取id列表
  //遍历selectedEmpList
  selectedEmpList.forEach((emp) => {
    deleteIds.value.push(emp.id);
  });
  //打印
  console.log(deleteIds.value);
  console.log(deleteIds.value.join(","));
};
//批量删除点击事件
const deleteBatch = () => {
  //如果没有勾选，提示用户勾选
  if (!deleteIds.value || !deleteIds.value.length) {
    ElMessage.warning("您还没有勾选要删除的数据，沐沐不知道要帮你删除哪些数据")
    return;
  }

  //弹出删除确认提示框
  ElMessageBox.confirm("您确认要删除当前选中的员工数据吗?","删除提示", {
    confirmButtonText:"确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      //点击确认回调函数
      //根据id调用异步删除员工请求
      //将数组deleteIds转换为使用分隔符","拼接成字符串
      let ids = deleteIds.value.join(",");
      let result = await deleteApi(ids);
      //判断是否成功
      if (result.code){
        //成功提示删除成功
        ElMessage.success("删除成功");
        //刷新页面重新查询
        queryPage();
      } else {
        //失败提示失败信息
        ElMessage.error(result.msg);
      }
    })
    .catch(() => {
      //取消回调函数
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
}
/*
//侦听方法1
const myname = ref<string>('')
watch(myname, (newVal,oldVal)=>{
  console.log(`name的值,newVal：${newVal},oldVal：${oldVal}`);
});
//侦听方法2：侦听对象的单个属性
//侦听empSearch对象中的name的变化
watch(() => empSearch.value.name, (newVal,oldVal)=>{
  console.log(`name的值, newVal：${newVal},oldVal：${oldVal}`);
});
//侦听对象的全部属性(深度侦听)
watch(empSearch,(newVal,oldVal)=>{
  console.log(`name的值,newVal：${newVal.name},oldVal：${oldVal.name}`);
},{deep: true})
*/
</script>

<template>
  <!-- 搜索栏 -->
  <el-form :inline="true" :model="empSearch" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="empSearch.name" placeholder="请输入姓名" />
    </el-form-item>

    <el-form-item label="性别">
      <el-select v-model="empSearch.gender" placeholder="请选择">
        <el-option label="男" value="1" />
        <el-option label="女" value="2" />
      </el-select>
    </el-form-item>

    <el-form-item label="入职时间">
      <el-date-picker
        v-model="empSearch.date"
        type="daterange"
        range-separator="到"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="queryPage">查询</el-button>
      <el-button @click="reset">重置</el-button>
    </el-form-item>
  </el-form>

  <!-- 功能按钮 -->
  <el-button type="success" @click="addPopDialog">+ 新增员工</el-button>
  <el-button type="danger" @click="">- 批量删除</el-button>
  <br><br>

  <!-- 列表展示 -->
  <el-table :data="empList" border style="width: 100%"
            fit
            @selection-change="handleSelectionChange">
<!--    添加复选框-->
    <el-table-column type="selection" width="55" />
    <el-table-column prop="name" label="姓名" align="center" width="130px" />
    <el-table-column prop="gender" label="性别" align="center" width="100px">
      <template #default="scope">
        {{ scope.row.gender == 1 ? "男" : "女" }}
      </template>
    </el-table-column>
    <el-table-column prop="image" label="头像" align="center">
      <template #default="scope">
        <img :src="scope.row.image" height="80px" />
      </template>
    </el-table-column>
    <el-table-column prop="deptName" label="所属部门" align="center" />
    <el-table-column prop="job" label="职位" align="center" width="100px">
      <template #default="scope">
        <span v-if="scope.row.job == 1">班主任</span>
        <span v-else-if="scope.row.job == 2">讲师</span>
        <span v-else-if="scope.row.job == 3">学工主管</span>
        <span v-else-if="scope.row.job == 4">教研主管</span>
        <span v-else-if="scope.row.job == 5">咨询师</span>
        <span v-else>其他</span>
      </template>
    </el-table-column>
    <el-table-column
      prop="entryDate"
      label="入职时间"
      align="center"
      width="130px" />
    <el-table-column prop="updateTime" label="最后修改时间" align="center" />
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" size="small" @click="upDateDialog(scope.row.id)">编辑</el-button>
        <el-button type="danger" size="small" @click="">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <br>

  <!-- 分页组件Pagination -->
  <el-pagination
    v-model:current-page="pagination.currentPage"
    v-model:page-size="pagination.pageSize"
    :page-sizes="[5, 10, 20, 50, 100]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="pagination.total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />

  <!-- 新增员工 / 修改员工的 DiaLog对话框 -->
  <el-dialog v-model="dialogFormVisible" title="新增员工">
    <el-form :model="emp">
      <!-- 第一行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" :label-width="labelWidth">
            <el-input v-model="emp.username" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" :label-width="labelWidth">
            <el-input v-model="emp.name" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" :label-width="labelWidth" prop="gender">
            <el-select v-model="emp.gender" placeholder="请选择" style="width: 100%;">
              <el-option :label="gender.name" :value="gender.value" v-for="gender in genderList" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" :label-width="labelWidth">
            <el-input v-model="emp.phone" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="薪资" :label-width="labelWidth">
            <el-input v-model="emp.salary" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期" :label-width="labelWidth">
            <el-date-picker v-model="emp.entryDate" type="date" placeholder="请选择入职日期" value-format="YYYY-MM-DD"
                            style="width: 100%;" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属部门" :label-width="labelWidth">
            <el-select v-model="emp.deptId" placeholder="请选择" style="width: 100%;">
              <el-option
                :label="dept.name"
                :value="dept.id"
                v-for="dept in deptList"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职位" :label-width="labelWidth">
            <el-select v-model="emp.job" placeholder="请选择" style="width: 100%;">
              <el-option
                :label="job.name"
                :value="job.id"
                v-for="job in jobList"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="头像" :label-width="labelWidth">
            <!--  文件上传 -->
            <!--
                  文件上传组件
                  action="/api/upload" 设置处理文件上传请求服务器地址
                  :show-file-list="false" 是否展现上传文件列表，false代表不展现
                  :on-success="handleAvatarSuccess"，服务器响应上传文件请求处理成功后触发事件函数，开发者通过这个函数获取服务器响应的数据
                  :before-upload="beforeAvatarUpload" 上传前调用的逻辑校验函数，校验文件后缀名和文件大小等信息
                  <img v-if="imageUrl" :src="imageUrl" class="avatar" /> 用于展现上传成功后的图片
                  -->
            <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="emp.image" :src="emp.image" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第六行 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="工作经历" :label-width="labelWidth">
            <el-button type="success" size="small" @click="addWorkItem"
            >+ 添加工作经历
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第七行 -->
      <el-row :gutter="5" v-for="expr in emp.exprList">
        <el-col :span="10">
          <el-form-item label="时间" size="small" :label-width="labelWidth">
            <el-date-picker
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD"
              v-model="expr.exprDate"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="公司" size="small">
            <el-input placeholder="公司名称" v-model="expr.company" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="职位" size="small">
            <el-input placeholder="职位名称" v-model="expr.job" />
          </el-form-item>
        </el-col>

        <el-col :span="2">
          <el-form-item size="small">
            <el-button type="danger" @click="delWorkItem(expr)"
            >- 删除
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveOrUpdate">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>